import { NextRequest, NextResponse } from 'next/server';
import { getDeviceParameterDb } from '@/lib/device-parameter-database';

// GET /api/field-metadata?tableName=table_c18
// GET /api/field-metadata?tableName=table_c18&dataSource=P
// GET /api/field-metadata?tableName=table_c18&measurementClass=转速
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const tableName = searchParams.get('tableName');
    const dataSource = searchParams.get('dataSource');
    const measurementClass = searchParams.get('measurementClass');
    const requiredOnly = searchParams.get('requiredOnly') === 'true';

    console.log('=== 字段元数据API调试 ===');
    console.log('请求参数:', { tableName, dataSource, measurementClass, requiredOnly });
    
    // 检查表名是否看起来正确
    if (tableName && !tableName.startsWith('table_')) {
      console.log('警告: 表名格式可能不正确:', tableName);
    }

    if (!tableName) {
      return NextResponse.json({
        success: false,
        error: '缺少表名参数'
      }, { status: 400 });
    }

    const db = getDeviceParameterDb();
    const deviceParameterDb = db as any;

    // 检查 parameter_field_metadata 表是否存在
    const tableExistsStmt = deviceParameterDb.db.prepare(`
      SELECT name FROM sqlite_master WHERE type='table' AND name='parameter_field_metadata'
    `);
    const tableExists = tableExistsStmt.get();
    console.log('parameter_field_metadata 表是否存在:', !!tableExists);

    if (!tableExists) {
      return NextResponse.json({
        success: false,
        error: 'parameter_field_metadata 表不存在，请先运行字段元数据初始化脚本'
      }, { status: 500 });
    }

    // 检查表中是否有数据
    const countStmt = deviceParameterDb.db.prepare(`
      SELECT COUNT(*) as count FROM parameter_field_metadata WHERE table_name = ?
    `);
    const countResult = countStmt.get(tableName);
    console.log(`表 ${tableName} 的字段元数据数量:`, countResult);

    let fields;
    if (dataSource) {
      fields = db.getFieldsByDataSource(tableName, dataSource);
    } else if (measurementClass) {
      fields = db.getFieldsByMeasurementClass(tableName, measurementClass);
    } else if (requiredOnly) {
      fields = db.getRequiredFields(tableName);
    } else {
      fields = db.getParameterTableFields(tableName);
    }

    console.log('获取到的字段数据:', fields);
    console.log('字段数量:', fields.length);
    
    // 如果字段数量为0，让我们检查可用的表
    if (fields.length === 0) {
      const allTablesStmt = deviceParameterDb.db.prepare(`
        SELECT DISTINCT table_name FROM parameter_field_metadata LIMIT 10
      `);
      const availableTables = allTablesStmt.all();
      console.log('数据库中可用的表:', availableTables);
      
      // 检查是否有类似的表名
      const similarTablesStmt = deviceParameterDb.db.prepare(`
        SELECT DISTINCT table_name FROM parameter_field_metadata WHERE table_name LIKE ?
      `);
      const similarTables = similarTablesStmt.all(`%${tableName}%`);
      console.log('类似的表名:', similarTables);
    }

    const tableMetadata = db.getTableMetadata(tableName);
    console.log('表元数据:', tableMetadata);

    return NextResponse.json({
      success: true,
      data: {
        tableMetadata,
        fields,
        fieldCount: fields.length
      }
    });
    
  } catch (error) {
    console.error('获取字段元数据失败:', error);
    return NextResponse.json({
      success: false,
      error: error instanceof Error ? error.message : '获取字段元数据失败'
    }, { status: 500 });
  }
}

// GET /api/field-metadata/summary - 获取元数据汇总信息
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { action } = body;
    
    const db = getDeviceParameterDb();
    
    if (action === 'summary') {
      const measurementClasses = db.getAllMeasurementClasses();
      const dataSources = db.getAllDataSources();
      
      return NextResponse.json({
        success: true,
        data: {
          measurementClasses,
          dataSources,
          dataSourceDescriptions: {
            'P': '采购数据 - 由采购部门提供的设备参数',
            'E': '工程数据 - 由工程设计部门确定的参数',
            'M': '制造数据 - 由制造商提供的技术参数',
            'O': '运维数据 - 由运维部门记录的参数'
          }
        }
      });
    }
    
    return NextResponse.json({
      success: false,
      error: '无效的操作'
    }, { status: 400 });
    
  } catch (error) {
    console.error('获取元数据汇总失败:', error);
    return NextResponse.json({
      success: false,
      error: error instanceof Error ? error.message : '获取元数据汇总失败'
    }, { status: 500 });
  }
}
